package com.louis.web.controller;

import java.lang.reflect.ParameterizedType;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.HandlerMapping;

import com.louis.dao.GeneralDao;

@SuppressWarnings("unchecked")
public abstract class AbstractController<T> implements Controller {

	private NativeWebRequest	nativeWebRequest;
	@Resource(name = "generalDao")
	private GeneralDao			generalDao;
	private String				redirectPath;
	private Class<T>			clazz;

	public static final String	SUFFIX	= ".html";

	public AbstractController() {
	}

	public String getPathVariable(String pathVarName) {
		HttpServletRequest request = getRequest();
		Map<String, String> uriTemplateVariables = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
		if (uriTemplateVariables == null) {
			return null;
		}
		return uriTemplateVariables.get(pathVarName);
	}

	public String redirect() {
		return "redirect:" + redirectPath + SUFFIX;
	}

	public void dataPrepare(ModelMap modelMap) {
	}

	public final HttpServletRequest getRequest() {
		return nativeWebRequest.getNativeRequest(HttpServletRequest.class);
	}

	public final HttpServletResponse getResponse() {
		return nativeWebRequest.getNativeResponse(HttpServletResponse.class);
	}

	public String getRedirectPath() {
		return redirectPath;
	}

	public void setRedirectPath(String redirectPath) {
		this.redirectPath = redirectPath;
	}

	public GeneralDao getGeneralDao() {
		return generalDao;
	}

	public void setGeneralDao(GeneralDao generalDao) {
		this.generalDao = generalDao;
	}

	public Class<T> getClazz() {
		if (clazz == null) {
			clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		}
		return clazz;
	}

	protected void addTipText(Object message) {
		getRequest().getSession().setAttribute("tipText", message);
	}

	public NativeWebRequest getNativeWebRequest() {
		return nativeWebRequest;
	}

	public void setNativeWebRequest(NativeWebRequest nativeWebRequest) {
		this.nativeWebRequest = nativeWebRequest;
	}
}
